// store/index.js
import { defineStore } from 'pinia'

export const useMainStore = defineStore('main', {
  state: () => ({
    
    age: 18,
    socketTask: null,
    isConnected: false,  // 连接状态
    messages: [],       // 消息队列
    reconnectAttempts: 0 // 重连计数
  }),
  actions: {
    // 初始化 WebSocket
    initWebSocket(url) {
      if (this.socketTask) return // 避免重复连接

      this.socketTask = uni.connectSocket({
        url,
        success: () => {
          console.log('WebSocket 连接成功')
          this.isConnected = true
          this.setupListeners() // 绑定事件监听
        },
        fail: (err) => {
          console.error('连接失败:', err)
          this.handleReconnect(url) // 失败时自动重连
        }
      })
    },

    // 绑定事件监听
    setupListeners() {
      this.socketTask.onOpen(() => {
        this.isConnected = true
        this.reconnectAttempts = 0 // 重置重连计数
        console.log('WebSocket 已打开')
      })

      this.socketTask.onMessage((res) => {
		  console.log("收到了消息：",res)
        this.messages.push(JSON.parse(res.data)) // 存储消息
		console.log(this.messages)
      })

      this.socketTask.onClose(() => {
        this.isConnected = false
        this.handleReconnect(this.socketTask.url) // 断开时自动重连
      })
    },

    // 处理重连逻辑
    handleReconnect(url) {
      if (this.reconnectAttempts >= 3) return // 最多重试3次
      
      setTimeout(() => {
        this.reconnectAttempts++
        console.log(`尝试第 ${this.reconnectAttempts} 次重连...`)
        this.initWebSocket(url)
      }, 3000) // 3秒后重连
    },

    // 发送消息
    sendMessage(data) {
      if (this.isConnected) {
        this.socketTask.send({
          data: JSON.stringify(data),
          success: (res) => console.log('消息发送成功:',res)
        })
      } else {
        console.error('WebSocket 未连接')
      }
    },

    // 关闭连接
    closeWebSocket() {
      if (this.socketTask) {
        this.socketTask.close()
        this.socketTask = null
        this.isConnected = false
      }
    }
  }
})